﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OpenQuarters.WebQuarters.Utils;

namespace OpenQuarters.WebQuarters.Core
{
    [Serializable]
    public class JFormResponse<T> where T : class
    {
        public static JFormResponse<T> Current
        {
            get { return SessionItem.GetItem<JFormResponse<T>>("JFormResponse<" + typeof(T).FullName + ">", () => null); }
            set { SessionItem.SetItem<JFormResponse<T>>("JFormResponse<" + typeof(T).FullName + ">", value); }
        }

        public T result = default(T);
        public bool success
        {
            get { return errorMessages.Count == 0; }
        }
        public FriendlyDictionary<string, List<string>> errorMessages = new FriendlyDictionary<string, List<string>>();
        public FriendlyDictionary<string, List<string>> messages = new FriendlyDictionary<string, List<string>>();

        private FriendlyDictionary<string, string> formParams;
        public FriendlyDictionary<string, string> FormParams
        {
            get { return formParams; }
            set { formParams = value; }
        }

        public JFormResponse(T result)
        {
            this.result = result;
            this.formParams = Utils.GeneralUtils.NameValueCollectionToDictionary(Oracle.Request.Form);
        }

        public JFormResponse()
        {
            this.formParams = Utils.GeneralUtils.NameValueCollectionToDictionary(Oracle.Request.Form);
        }

        public JFormActionFilter<T> Return()
        {
            return new JFormActionFilter<T>(this);
        }
    }

    public static class JFormResponse
    {
        public static JFormResponse<T> AttemptBind<T>(string Json) where T : class
        {
            return AttemptBind<T>(Json, null);
        }

        public static JFormResponse<T> AttemptBind<T>(string Json, T ExistingObject) where T : class
        {
            JFormResponse<T>.Current = new JFormResponse<T>();
            T obj = GeneralUtils.FromJSON<T>(Json, ExistingObject);
            
            var r = JFormResponse<T>.Current;
            r.result = obj;
            
            JFormResponse<T>.Current = null;
            
            return r;
        }
    }
}
